/****************************************************************************
 *
 * Copyright (C) 2003-2008 Los Alamos National Security, LLC
 *                         Packet Analytics Corporation
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License Version 2 as
 * published by the Free Software Foundation.  You may not use, modify or
 * distribute this program under any other version of the GNU General
 * Public License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 *
 ****************************************************************************/
package nfse.gui.client;

import com.gwtext.client.widgets.Panel;
import com.gwtext.client.widgets.Toolbar;
import com.gwtext.client.widgets.*;
import com.gwtext.client.widgets.event.*;
import com.gwtext.client.data.*;    
import com.gwtext.client.widgets.grid.ColumnConfig;  
import com.gwtext.client.widgets.grid.ColumnModel;  
import com.gwtext.client.widgets.grid.GridPanel;  
import com.gwtext.client.widgets.grid.event.*;
import com.gwtext.client.core.EventObject; 
import com.gwtext.client.core.*;
import java.util.*;

import nfse.gui.client.data.*;
   
public class CriticalServersGrid extends Panel
{
	private int height;
	private HashMap dataMap;
	private CriticalServerEntries criticalServerEntries;
	private HeadsUpTab headsUpTab;
	private GridPanel grid;
	private ToolbarTextItem text;
	private ArrayList columnTypeIdList = new ArrayList();
	private ArrayList columnNameList;
	
	public CriticalServersGrid(int height, int width)
	{
		//this.setHeight(height);
	    this.height = height + 5;
		this.setWidth(width);
		this.setBorder(true);
	}
	
	public void buildGrid(HashMap dataMap, HeadsUpTab headsUpTab)
	{
		this.headsUpTab = headsUpTab;
		this.dataMap = dataMap;
		buildGrid();
	}
	
	public void buildGrid(CriticalServerEntries criticalServerEntries, HeadsUpTab headsUpTab)
	{
		this.headsUpTab = headsUpTab;
		this.criticalServerEntries = criticalServerEntries;
		buildGrid();
	}
	
	
	private RecordDef buildRecordDef()
	{	
		FieldDef[] sfd = new StringFieldDef[columnNameList.size() + 1];
		
		sfd[0] = new StringFieldDef("Address");
		
		for (int i = 0; i < columnNameList.size(); i++)
		{
			sfd[i + 1] = new StringFieldDef((String)columnNameList.get(i));
		}					
		
		RecordDef recordDef = new RecordDef(sfd);

		return recordDef;
	}
	
	
	private ColumnModel getColumnModel()
	{
		ColumnConfig[] columnConfig;
		
		if (columnNameList.size() == 0)			
		    columnConfig = new ColumnConfig[columnNameList.size() + 2];
		else
			columnConfig = new ColumnConfig[columnNameList.size() + 1];
		
		 
			ColumnConfig ccAddress = new ColumnConfig("Address","Address",100);
			ccAddress.setCss("gwt-cell-link;");
			columnConfig[0] = ccAddress;
			
			if (columnNameList.size() == 0)
			{
				ColumnConfig ccNoData = new ColumnConfig("NetFlow","NetFlow",100);
				columnConfig[1] = ccNoData;
			}
			
			for (int i = 0; i < columnNameList.size(); i++)
			{
				ColumnConfig cc = new ColumnConfig((String)columnNameList.get(i),(String)columnNameList.get(i),75);
				cc.setAlign(TextAlign.RIGHT);
				columnConfig[i + 1] = cc;
			}					

			 ColumnModel columnModel = new ColumnModel(columnConfig);

		return columnModel;
	}
	
	
	public void buildGrid()
	{	

//		ArrayList aList = new ArrayList();
//		aList.add("Address");
//		//aList.add("proofPoint");
//		aList.add("Firewall");
//		//aList.add("snort");
//		aList.add("NetFlow");

//		buildColumnList(); //Iterate through the list of type_id from the dataMap
		setColumnNameList(); //This generates the columnNameList
		
		grid = new GridPanel();	
		
		grid.addGridCellListener(new GridCellListenerAdapter() 
		{  
			            public void onCellClick(GridPanel grid, int rowIndex, int colIndex, EventObject e) 
			            {
			            	if (colIndex == 0)
			            		openQuery(rowIndex);
			            }  
		}
		
		);  
		
		
		Object[][] data = convertRawDataToObjectGrid();

		//The columns names are not determined until after the data Object[][] has been processed
		RecordDef recordDef = buildRecordDef();
		
		
		if (data != null)
		{
			MemoryProxy proxy = new MemoryProxy(data);
			
			ArrayReader reader = new ArrayReader(recordDef);
			Store store = new Store(proxy,reader);
			store.load();
			grid.setStore(store);		
		}
		
 
		ColumnModel columnModel = getColumnModel();
		
		 grid.setColumnModel(columnModel);  
		 grid.setFrame(true); 
		 
		 grid.setStripeRows(true); 
		 grid.setAutoScroll(true);
		 //grid.setAutoExpandColumn("Address");  
		 //grid.setHeight(height);
		 grid.setHeight(350);
		 //grid.setWidth(5);  
		 grid.setTitle("Critical Servers");
		 
			Toolbar tBar = new Toolbar();
			ButtonListenerAdapter listener = new ButtonListenerAdapter() {  
			public void onClick(Button button, com.gwtext.client.core.EventObject e) {
				System.out.println("The critical servers refresh button was clicked");
				refreshThis();
				//updateFooterTimeStamp();
			}
			};
			
			ToolbarButton refreshBtn = new ToolbarButton("Refresh",listener);
			tBar.addButton(refreshBtn);
			grid.setBottomToolbar(tBar);
		 this.add(grid);                                           
				
		       
	}
	
	public void openQuery(int index)
	{
		CriticalServer cs = criticalServerEntries.entries[index];
		headsUpTab.openQueryPanel(cs.getQueryId());
	}
	
	public void refreshThis()
	{
		this.headsUpTab.refreshCriticalServersGrid();
	}
	
	
	public void refreshGrid(HashMap dataMap)
	{
		this.dataMap = dataMap;
		
		RecordDef recordDef = buildRecordDef();
						
		Object[][] data = convertRawDataToObjectGrid();
		
		
		if (data != null)
		{
			MemoryProxy proxy = new MemoryProxy(data);
			
			ArrayReader reader = new ArrayReader(recordDef);
			Store store = new Store(proxy,reader);
			store.load();
			
			ColumnModel columnModel = getColumnModel();
			 grid.reconfigure(store, columnModel);			
		}
	}

	public void refreshGrid(CriticalServerEntries criticalServerEntries)
	{
		this.criticalServerEntries = criticalServerEntries;
		
		RecordDef recordDef = buildRecordDef();
						
		Object[][] data = convertRawDataToObjectGrid();
		
		
		if (data != null)
		{
			MemoryProxy proxy = new MemoryProxy(data);
			
			ArrayReader reader = new ArrayReader(recordDef);
			Store store = new Store(proxy,reader);
			store.load();
			
			ColumnModel columnModel = getColumnModel();
			 grid.reconfigure(store, columnModel);			
		}
	}
	
	

//	private void buildColumnList()
//	{
//		if (dataMap != null)
//		{
//			Iterator it = dataMap.keySet().iterator();
//			while (it.hasNext())
//			{
//				String ip = (String)it.next();
//				ArrayList ipRecordOfHitsByDataTypeList = (ArrayList)dataMap.get(ip);
//				
//				for (int i = 0; i < ipRecordOfHitsByDataTypeList.size(); i++)
//				{
//					CriticalServer criticalServer = (CriticalServer)ipRecordOfHitsByDataTypeList.get(i);
//					addType(criticalServer.getDataType());
//				}
//			}					
//		}
//		
//		
//	}
	
	private void addType(String typeId)
	{
		
		for (int i = 0; i < columnTypeIdList.size(); i++)
		{
			String columnId = (String)columnTypeIdList.get(i); 
			if (columnId.equals(typeId))
				return;
		}
		columnTypeIdList.add(typeId);
	}


	private void setColumnNameList()
	{
		if (criticalServerEntries != null)
		{			
			columnNameList = new ArrayList();
			for (int i = 0; i < criticalServerEntries.typeNames.length; i++)
			{
				columnNameList.add(criticalServerEntries.typeNames[i]);			
			}
		}
	}

//	private void setColumnNameList()
//	{
//		columnNameList = new ArrayList();
//		for (int i = 0; i < columnTypeIdList.size(); i++)
//		{
//			SensorTypes st = (SensorTypes)headsUpTab.getSensorTypesMap().get((String)columnTypeIdList.get(i));			
//			columnNameList.add(st.getTypeName());			
//		}
//	}

		
		/**
		 * This converts the incoming data object a HashMap or an ArrayList into a Object[][]
		 */
		private Object[][] convertRawDataToObjectGrid()
		{
			int columns = columnNameList.size() + 1;
			
			Object[][] displayData = null;
			
			if ((criticalServerEntries != null) && (criticalServerEntries.entries != null))
			{
				displayData = new Object[criticalServerEntries.entries.length][columns];
				
				CriticalServer criticalServer = null;
				int recordCount = 0;
				for (int i = 0; i < criticalServerEntries.entries.length; i++)
				{					
					criticalServer = criticalServerEntries.entries[i];
					displayData[recordCount][0] = criticalServer.getIp();  
									
					for (int j = 0; j < criticalServer.counts.length; j++)
					{
						
						displayData[recordCount][j + 1] = criticalServer.counts[j] + "";
					
					}
					recordCount++;
				}					
				
			}
			else
			{
				displayData = new Object[1][1];
			}
			
			return displayData;
		}
		
		
		
	
//	/**
//	 * This converts the incoming data object a HashMap or an ArrayList into a Object[][]
//	 */
//	private Object[][] convertRawDataToObjectGrid2()
//	{
//		int columns = columnNameList.size() + 1;
//		
//		Object[][] displayData = null;
//		
//		if (dataMap != null)
//		{
//			displayData = new Object[dataMap.size()][columns];
//			
//			int recordCount = 0;
//			CriticalServer criticalServer = null;
//			
//			Iterator it = dataMap.keySet().iterator();
//			while (it.hasNext())
//			{
//				String ip = (String)it.next();
//				ArrayList ipRecordOfHitsByDataTypeList = (ArrayList)dataMap.get(ip);
//				
//				displayData[recordCount][0] =  ip;
//								
//				for (int i = 0; i < ipRecordOfHitsByDataTypeList.size(); i++)
//				{
//					criticalServer = (CriticalServer)ipRecordOfHitsByDataTypeList.get(i);
//					displayData[recordCount][i + 1] =  criticalServer.getCount();
//				
//				}
//				recordCount++;
//			}					
//		}
//		else
//		{
//			displayData = new Object[1][1];
//		}
//		
//		return displayData;
//	}
	
	public GridPanel getGrid()
	{
		return grid;
	}


	public void setGrid(GridPanel grid)
	{
		this.grid = grid;
	}

	
}				
	
